﻿PuppetPlay.ImageCache = (function (cfg) {
    var canvasWidth = 2000, canvasHeight = 3000;
    var cacheCanvas = document.createElement('canvas');
    //document.body.appendChild(cacheCanvas);
    cacheCanvas.width = canvasWidth;
    cacheCanvas.height = canvasHeight;
    
    var offsetX = 0, offsetY = 0, floorH = 0;
    var cacheMap = {};
    var idCounter = 0;
    return {
        loadImages: function(callback){
            var images = PuppetPlay.Sources.Images;
            var imageCount = 0;
            for (var rsName in images) {
                for (var k in images[rsName]) {
                    imageCount++;
                }
            }
            console.log(imageCount + ' images to load.');
        
            var loadedCount = 0;
            for (var rsName in images) {
                var rs = images[rsName];
                for (var k in rs) {
                    rs[k].obj = new Image();
                    rs[k].obj.onload = function () {
                        console.log(loadedCount + 1 + ') ' + this.src + ' loaded.');
                        if (++loadedCount >= imageCount) {
                            console.log('All images loaded.');
                            if(callback){
                                callback();
                            }
                        }
                    };
                    rs[k].obj.src = rs[k].src;
                }
            }
        },
        
        genImageId: function(){
            return ++idCounter;
        },
        
        getCanvas: function(){
            return cacheCanvas;
        },
        
        hasCache: function(imgId){
            return imgId in cacheMap;
        },
        
        getCache: function(imgId){
            return cacheMap[imgId];
        },
        
        drawImage: function(id, img, w, h){
            if(offsetX + w > canvasWidth){
                offsetX = 0;
                offsetY += floorH;
                floorH = 0;
            }
            cacheCanvas.getContext('2d').drawImage(img, offsetX, offsetY, w, h);            
            cacheMap[id] = {
                x: offsetX,
                y: offsetY
            };
            
            offsetX += w;
            if(h > floorH){
                floorH = h;
            }
        }
    };
})();